package repository;

import annotation.DependencyInjection;
import annotation.Singleton;
import database.UserDatabase;
import entity.User;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Singleton
public class UserRepository {
    private UserDatabase database;

    @DependencyInjection
    public UserRepository(UserDatabase database) {
        this.database = database;
    }

    public void startWrite() {
        database.startWrite();
    }

    public void endWrite() {
        database.endWrite();
    }

    public void startRead() {
        database.startRead();
    }

    public void endRead() {
        database.endRead();
    }

    public User getByUsername(String username) {
        User result = database.getList().stream().filter(user -> user.getUsername().equals(username)).findAny().orElse(null);
        if (result == null) {
            return null;
        }

        return new User(result);
    }

    public boolean add(User user) {
        if (user == null) {
            return false;
        }
        User result = database.getList().stream().filter(currentUser -> currentUser.getUsername().equals(user.getUsername())).findAny().orElse(null);
        if (result != null) {
            return false;
        }
        database.getList().add(user);
        return true;
    }

    public boolean changeNickname(String username, String nickname) {
        Optional<User> result = database.getList().stream().filter(user -> user.getUsername().equals(username)).findAny();
        if (!result.isPresent()) {
            return false;
        }
        User user = result.get();
        user.setNickname(nickname);
        return true;
    }

    public boolean changePassword(String username, String newPassword) {
        Optional<User> result = database.getList().stream().filter(user -> user.getUsername().equals(username)).findAny();
        if (!result.isPresent()) {
            return false;
        }
        User user = result.get();
        user.setPassword(newPassword);
        return true;
    }

    public List<User> getAllUsers() {
        return database.getList().stream().map(User::new).collect(Collectors.toList());
    }
}
